package leetcode.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangmaolin1
 * @date 2021/12/29 下午10:42
 */
public class _257二叉树的所有路径 {

    public static List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        path(root, "", result);

        return result;
    }

    private static void path(TreeNode root, String node, List<String> result) {
        node = node.equals("") ? node + root.val : node + "->" + root.val;
        if (root.left == null && root.right == null) {
            result.add(node);
            return;
        }
        if (root.left != null) {
            path(root.left, node, result);
        }
        if (root.right != null) {
            path(root.right, node, result);
        }
    }

    /**
     * StringBuilder减少字符串拷贝耗时
     */
    private void path2(TreeNode root, String node, List<String> result) {
        StringBuilder sb = new StringBuilder(node);
        sb.append(root.val);
        if (root.left == null && root.right == null) {
            result.add(sb.toString());
            return;
        }
        sb.append("->");
        if (root.left != null) {
            path(root.left, sb.toString(), result);
        }
        if (root.right != null) {
            path(root.right, sb.toString(), result);
        }
    }

    public static void main(String[] args) {
        TreeNode result = new TreeNode(1);
        result.left = new TreeNode(2);
        result.left.right = new TreeNode(5);
        result.right = new TreeNode(3);
        binaryTreePaths(result);
    }

}
